/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package knowledgebase.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import knowledgebase.dao.DocumentDAO;
import knowledgebase.model.Document;
import knowledgebase.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 *
 * @author eugene
 */
@Service("documentService")
public class DocumentServiceImpl implements DocumentService {

    Log log = LogFactory.getLog(getClass());
    @Autowired
    private DocumentDAO documentDAO;
    @Autowired
    private UserService userService;

    @Override
    public String saveOrUpdateDocument(String docId, String title, String hierarchy) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String ownerName = (principal instanceof Assembler) ? ((Assembler)principal).getUsername() : "";
        User owner = userService.findUserByName(ownerName);
        boolean isCreate = docId == null || docId.equals("");
        try {
            docId = isCreate ? UUID.randomUUID().toString() : UUID.fromString(docId).toString();
        } catch (Exception ex) {
            docId = UUID.randomUUID().toString();
        }
        Document doc = new Document(docId, title, hierarchy, new Date(), owner);
        if (isCreate) {
            return documentDAO.saveDocument(doc);
        } else {
            documentDAO.updateDocument(doc);
            return docId;
        }
    }

    @Override
    public void removeDocument(String docId) {
        documentDAO.removeDocument(docId);
    }

    @Override
    public List<Document> findDocumentsByTitle(String docTitle) {
        return documentDAO.findDocumentsByTitle(docTitle);
    }

    @Override
    public void updateDocumentHierarchy(String docId, String hierarchy) {
        documentDAO.updateDocumentHierarchy(docId, hierarchy);
    }

    @Override
    public List<Document> getDocumentsByOwner(User owner) {
        return documentDAO.getDocumentsByOwner(owner);
    }
    
    @Override
    public Document getDocumentById(String id) {
        return documentDAO.getDocumentById(id);
    }
    
    @Override
    public List<Document> getAllDocuments() {
        return documentDAO.getAllDocuments();
    }
}
